<?php
namespace Jykj\Quicklogin\Controller;

/***************************************************************
 *
 *  Copyright notice
 *
 *  (c) 2015 WHB <wanghongbin@ngoos.org>
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

/**
 * The Controller for  QQ
 */
class QQController extends CommonController{

	
	/**
	 * 远程登录成功后回调
	 */
	public function callbackAction(){
		
		$url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=".$this->settings['qq']['appId']."&client_secret=".$this->settings['qq']['appKey']."&code=".$_GET['code']."&state=".$_GET['state']."&redirect_uri=".urlencode(\TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'));
		
		$str = $this->get_contents($url);
		parse_str($str);
		
		//获取唯一ID (openid)
		$openiduri = "https://graph.qq.com/oauth2.0/me?access_token=".$access_token;
		$response = $this->get_contents($openiduri);
		
		
		 //--------检测错误是否发生
        if(strpos($response, "callback") !== false){
            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response = substr($response, $lpos + 1, $rpos - $lpos -1);
        }

        $openuser = json_decode($response);
        if(isset($openuser->error)){
			return new \TYPO3\CMS\Extbase\Error\Error('登录错误 ,请重新登录', 1340193849); 
        }else{
			
			//获取用户信息
			$openiduri = "https://graph.qq.com/user/get_user_info?access_token=".$access_token."&oauth_consumer_key=".$this->settings['qq']['appId']."&openid=".$openuser->openid;
			$userinfo = $this->get_contents($openiduri);
			$userinfo = json_decode($userinfo);
			
			if($userInfo = $this->quickUserRepository->findByOpenid($openuser->openid,'openidQq')){ //判断是否已绑定，未绑定进行绑定
				
				$userInfo->setAccessTokenQq($access_token);
				$this->quickUserRepository->update($userInfo);
				$this->redirect('login',NULL,NULL,array('fuser'=>$userInfo,'nickname'=>$userinfo->nickname,'from'=>$this->request->getArgument('from')));
			}else{
				
				$this->redirect('bind',NULL,NULL,array('access_token' => $access_token, 'openid' => $openuser->openid, 'nickname'=>$userinfo->nickname,'from'=>$this->request->getArgument('from')));
			}
			
		}
	}
}